<?php
/**
 * Created by PhpStorm.
 * User: harlen
 * Date: 2017/2/8 0008
 * Time: 14:07
 */
namespace app\admin\controller;

use app\admin\model\Article as ArticleModel;
use app\admin\model\Files as FilesModel;

use app\admin\model\ArticleContent;

class Article extends BaseController
{
    protected $param, $id, $post, $articleModel;
    protected $url = 'article/index';

    public function __construct(\think\Request $request)
    {

        $this->param = $request->param();
        $this->post = $request->post();
        $this->articleModel = new ArticleModel();
        $this->id = isset($this->param['id']) ? intval($this->param['id']) : '';
        parent::__construct();

    }

    /**
     * 获取文章列表
     * @return mixed
     */
    public function index()
    {
        //获取分页数据
        $list = ArticleModel::paginate(20);
        $this->assign([
            'list' => $list,
            'page' => $list->render(),
        ]);

        return $this->fetch();
    }

    /**
     * 添加文章
     * @return mixed|void
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            //验证
            $result = $this->validate($post, [
                ['title|标题', 'require|min:5|max:125'],
                ['category_id|分类', 'require'],
            ]);
            if (true !== $result) {
                return ['code' => 0, 'msg' => $result];
            }
            $post['user_id'] = $this->uid;
            $insert = $this->articleModel->create($post);//增加
            if ($insert) {
                //添加内容到content表
                ArticleContent::create(['article_id' => $insert['id'], 'content' => input('post.content', '', '')], 'content,article_id');
                //如果有封面信息。 对文件表进行操作
                if($post['cover_id'] != ''){
                    $clover_ids = explode(',', $post['cover_id']);
                    $filesModel = new FilesModel();
                    $id = $this->articleModel->getLastInsID();
                    foreach($clover_ids as $v){
                        if($v != ''){
                            $filesModel->isUpdate(true, ['id'=>$v])->save([
                                'is_bind' => 1,
                                'relation_id'=>$id,
                                'relation_model'=> 'Article'
                            ]);
                        }
                    }
                }

                return ['code'=>1, 'msg'=>lang('add success'), 'url'=>url($this->url)];
            } else {
                return ['code'=>0, 'msg'=>lang('failed')];
            }
        }

        return $this->fetch('');
    }

    /**
     * 编辑文章
     * @return mixed|void
     */
    public function edit()
    {
        $id = $this->id;
        $info = articleModel::get($id);
        if ($this->request->isPost()) {
            $post = $this->request->post();
            //验证
            $result = $this->validate($post, [
                ['title|标题', 'require|min:5|max:125'],
                ['category_id|分类', 'require'],
            ]);
            if (true !== $result) {
                return ['code' => 0, 'msg' => $result];
            }
            foreach ($post as $k => $val) {
                $info->$k = $val;
            }
            $info->user_id = $this->uid;
            $info->id = $id;

            //如果关联表，或者主表有一个修改成功，就返回成功。
            if ($info->save() | $info->hasOneArticleContent->save(['content' => input('post.content', '', '')])) {
                return ['code'=>1, 'msg'=>lang('save success'), 'url'=>url($this->url)];
            } else {
                return ['code'=>0, 'msg'=>lang('save failed')];
            }

        }
        $this->assign('info', $info);

        return $this->fetch();
    }

    /**
     * 删除文章
     */
    public function delete()
    {
        $id = $this->id;
        if (!$this->request->isAjax()) {
            return abort(404, lang('404 denied access'));
        }
        $info = ArticleModel::get($id);
        //关联删除文章内容
        //TODO::加入点赞评论的删除
        if ($info->together('hasOneArticleContent')->delete()) {

            //TODO::删除文章和相关评论等信息

            //$this->articleModel->deleteArticle();
            return ['code'=>1, 'msg'=>lang('delete success'), 'url'=>url($this->url)];
        } else {
            return ['code'=>0, 'msg'=>lang('delete failed')];
        }
    }

    /**
     * 文章状态修改
     */
    public function status()
    {
        //这里的id是一个字符串
        $param = $this->param['param'];
        $id = $this->param['id'];

        if (!$this->request->isAjax()) {
            return abort(404, lang('404 denied access'));
        } else if (empty($id)) {
            return ['code' => 0, 'msg' => lang('Data cannot be empty')];
        }

        $ratify = $this->articleModel->allowField(['status'])->save(['status' => $param], ['id' => ['in', $id]]);

        if ($ratify) {
            return ['code'=>1, 'msg'=>lang('success'), 'url'=>url($this->url)];
        } else {
            return ['code'=>0, 'msg'=>lang('failed')];
        }
    }
}